package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
@Autowired
private ClazzService clazzService;
    /**
     * 条件分页查询
     * @param student
     * @return
     */
    @Override
    public PageResult pageQuery(StudentQueryParam param) {
        Page<Student> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        Page<Student> studentPage = lambdaQuery().like(StrUtil.isNotBlank(param.getName()), Student::getName, param.getName())
                .eq(ObjectUtil.isNotEmpty(param.getDegree()), Student::getDegree, param.getDegree())
                .eq(ObjectUtil.isNotEmpty(param.getClazzId()), Student::getClazzId, param.getClazzId())
                .page(page);
        //处理班级名称和违纪情况
        List<Student> studentList = studentPage.getRecords();
        Set<Integer> clazzIds = studentList.stream().map(Student::getClazzId).collect(Collectors.toSet());
        List<Clazz> clazzList = clazzService.listByIds(clazzIds);
        Map<Integer, String> clazzMap = clazzList.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
        studentList.forEach(student -> {
            student.setClazzName(clazzMap.getOrDefault(student.getClazzId(), "暂未分配班级"));
        });
        return new PageResult<>(studentPage.getTotal(), studentList);
    }

    /**
     * 扣分
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        Student student = lambdaQuery().eq(Student::getId, id).one();
        student.setViolationScore((short) (student.getViolationScore() + score));
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }
}
